<template>
  <div class="profile">
    <el-card>
      <template #header>
        <span>个人信息</span>
      </template>
      
      <div class="profile-content">
        <div class="avatar-section">
          <el-avatar 
            :size="100" 
            :src="getAvatarUrl(userStore.userInfo?.avatar)"
            @error="handleAvatarError"
          >
            {{ userStore.userInfo?.name?.charAt(0) }}
          </el-avatar>
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            accept="image/*"
          >
            <el-button type="primary">更换头像</el-button>
          </el-upload>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="姓名">{{ userStore.userInfo?.name }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ userStore.userInfo?.studentId }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ userStore.userInfo?.sex === 0 ? '男' : '女' }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ userStore.userInfo?.age }}</el-descriptions-item>
          <el-descriptions-item label="星座">{{ userStore.userInfo?.constellation }}</el-descriptions-item>
          <el-descriptions-item label="学校">{{ userStore.userInfo?.schoolName }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ userStore.userInfo?.major }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ userStore.userInfo?.email }}</el-descriptions-item>
          <el-descriptions-item label="余额">¥{{ userStore.userInfo?.balance || 0 }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ userStore.userInfo?.status === 1 ? '正常' : '限制' }}</el-descriptions-item>
          <el-descriptions-item label="自我介绍" :span="2">{{ userStore.userInfo?.introduction || '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="注册时间" :span="2">{{ userStore.userInfo?.createTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { useUserStore } from '../../stores/user'
import { ElMessage } from 'element-plus'
import api from '../../utils/api'
import { getAvatarUrl } from '../../utils/avatar'

const userStore = useUserStore()

// 上传配置
const uploadUrl = computed(() => `${api.defaults.baseURL}/user/avatar`)
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = async (response) => {
  console.log('上传响应:', response)
  if (response.code === 200) {
    ElMessage.success('头像上传成功')
    try {
      // 刷新用户信息（这会从服务器获取最新的用户数据包括头像）
      const result = await userStore.getUserInfo()
      if (result.success) {
        console.log('用户信息已更新:', userStore.userInfo)
      }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      ElMessage.warning('头像上传成功，但用户信息更新失败')
    }
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 上传失败
const handleUploadError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败')
}

// 头像加载失败处理
const handleAvatarError = (error) => {
  console.warn('头像加载失败:', error)
  // 不显示错误消息，让组件显示默认头像
}
</script>

<style scoped>
.profile {
  padding: 20px;
}

.profile-content {
  display: flex;
  gap: 30px;
}

.avatar-section {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}
</style>
